/*
 * @Author: 江舟
 * @LastEditors: 江舟 jijiangzhou@recycloud.cn
 * @LastEditTime: 2024-08-08 10:00:39
 * @Description: file content
 */
import EnOrDecrypt from './enOrDecrypt';

const EnOrDecryptInstance = new EnOrDecrypt();

class EnDecryptAdapter {
    private isEncrypt;
    constructor() {
        this.isEncrypt = null;
    }
    requestAdapter(config) {
        const { headers = {}, params = {} } = config;
        let { data = {} } = config;
        const isEncryptStatus = this.isEncrypt;

        if (headers['Content-Type'] === 'multipart/form-data') {
            // 导出
            const curdata = JSON.parse(data);
            EnOrDecryptInstance.getEnKey(curdata.timeStamp, curdata.transId);
            curdata.data = EnOrDecryptInstance.encryptFunc(JSON.stringify(curdata.data));
            data = JSON.stringify(curdata);
        } else if (config.method.toUpperCase() === 'GET') {
            if (isEncryptStatus) {
                EnOrDecryptInstance.getEnKey(params.timeStamp, params.transId);
                params.data = EnOrDecryptInstance.encryptFunc(params.data);
            }
        } else if (config.method.toUpperCase() === 'POST') {
            if (isEncryptStatus) {
                const curdata = JSON.parse(data);
                EnOrDecryptInstance.getEnKey(curdata.timeStamp, curdata.transId);
                curdata.data = EnOrDecryptInstance.encryptFunc(JSON.stringify(curdata.data));
                data = JSON.stringify(curdata);
            }
        }

        return {
            ...config,
            headers,
            params,
            data,
        };
    }
    respondseAdapter(response) {
        const { data: res } = response;
        if (typeof res?.data === 'string') {
            EnOrDecryptInstance.getEnKey(res.reqTimeStamp, res.traceId);
            const data = EnOrDecryptInstance.decipherFunc(res.data);
            response.data.data = data;
        }
        return response;
    }

    async init({ getIsEncrypt }) {
        if (typeof this.isEncrypt !== 'boolean') {
            try {
                const res = await getIsEncrypt();
                this.isEncrypt = res;
                return res;
            } catch (error) {
                console.error(error);
            }
        }
    }
}

export default EnDecryptAdapter;
